package softtech.apps.autoanswerphonecall;

import java.io.File;
import java.io.IOException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;

public class MyBroadcast extends BroadcastReceiver {

	static final String TAG = "MY BROADCAST";
	
	Context context;
	
	private final String AUDIO_RECORDER_FOLDER = "VoiceMessage";
	// Recording
	private final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
	private final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
	private MediaRecorder recorder = null;

	private File folder;
	private File files[];
	
	private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
			MediaRecorder.OutputFormat.THREE_GPP };
	private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4,
			AUDIO_RECORDER_FILE_EXT_3GP };

	private int currentFormat = 0;

	AudioManager audioManager;
	boolean recording = false;
	String file_path = "";
	
	static int statusRecord; 
	
	DatabaseHandler db;
	int Maxduration_id;
	int Maxduration;
	
	public MyBroadcast(Context ctx)
	{
		super();
		context = ctx;
		statusRecord = -1;
		String filepath = Environment.getExternalStorageDirectory().getPath();
		folder = new File(filepath, AUDIO_RECORDER_FOLDER);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		files = folder.listFiles();
		
		db = new DatabaseHandler(context);
		
		Config cfgMaxduration = db.getConfig(6);
		if (!cfgMaxduration.equals(null)
				&& cfgMaxduration != null) {
			Maxduration = cfgMaxduration.get_value();
			Maxduration_id = cfgMaxduration.get_id();

		}
		Log.d("VOICE", "Max time duration choice =" + Maxduration);
	}
	
	@Override
	public void onReceive(Context ctx, Intent intent) {
		context =ctx;
		
		Log.e(TAG,intent.getAction().toString());
		
		// TelephonyManager.EXTRA_INCOMING_NUMBER
		
		try {
			String result = intent.getExtras().getString(ConstantApp.RECORD_EXTRA_NAME);
			if (result.trim().equals("stopHere") && statusRecord == 1 ) {
				statusRecord = -1;
				stopRecording();
				
				generateNotification(context,"Vua moi ghi file = "+ file_path);
				Log.d(TAG,"Stop record voice message here");
				Log.d(TAG, "File vua duoc ghi = "+file_path);
			}else if (result.trim().equals("startHere") && statusRecord == -1) {
				statusRecord = 1;
				startRecording();
				Log.d(TAG,"--> Start record voice message here");	
			}

		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
			Log.d("FINISH", "Finish & exist");			
		}
		
	}
	
	/**
	 * Start recording a incoming call with input from
	 * MediaRecorder.AudioSource.MIC
	 * 
	 * @param recorder
	 * */
	public void startRecording() {
		/**
		 * Device audio manager
		 * */
		AudioManager am = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		am.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
				am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), 0);
		
		am.setMode(AudioManager.MODE_IN_CALL);
		am.setSpeakerphoneOn(true);
		/**
		 * Recorder manager
		 * */
		recorder = new MediaRecorder();
		
        
		// recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setOutputFormat(output_formats[currentFormat]);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		int maxtime = (Maxduration + 1) * 1000;
		recorder.setMaxDuration(maxtime); // 20 seconds
		file_path = getFilename();
		recorder.setOutputFile(getFilename());
		recorder.setOnErrorListener(errorListener);
		recorder.setOnInfoListener(infoListener);
		
		Log.d(TAG, "Max time duration = "+maxtime);
		
		/**
		 * Starting
		 * */
		try {
			Log.e("PREPARE GHI FILE","PREPARE GHI FILE");
			recorder.prepare();
			recorder.start();
			recording = true;
			Log.e("PREPARE GHI FILE","DA GHI FILE");
		} catch (IllegalStateException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
		
		
		Log.d("RECORD_INTENT", "Bat dau ghi am");

	}

	/**
	 * Stop a recorder and finish activity, add output file to wish list
	 * 
	 * @param recorder
	 * */
	public void stopRecording() {
		if (null != recorder && recording) {
			Log.d("RECORDING", "Stop recoding !!!! ");
			// filePath = getFilename();
			recorder.stop();
			recorder.reset();
			recorder.release();
			recorder = null;
			
		}
	}

	private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
		@Override
		public void onError(MediaRecorder mr, int what, int extra) {
			// Toast.makeText(VoiceManagerActivity.this,
			// "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
			Log.e("ERROR", "Loi trong qua trinh ghi am ");
			Log.e("ERROR", "Error: " + what + ", " + extra);
		}
	};

	private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
		@Override
		public void onInfo(MediaRecorder mr, int what, int extra) {
			// Toast.makeText(VoiceManagerActivity.this,
			// "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
			// .show();
		}
	};
	
	/**
	 * Return the path of voice message to store
	 * 
	 * @param AUDIO_RECORDER_FOLDER
	 * */
	public String getFilename() {
		File file = folder;
		if (!file.exists()) {
			file.mkdirs();
		}

		// return (file.getAbsolutePath() + "/" + "Audio-Record-"
		// +System.currentTimeMillis() + file_exts[currentFormat]);
		return (file.getAbsolutePath() + "/" + "From-"+PhoneCallReceiver.phoneNumber
				+"-"+ System.currentTimeMillis() + file_exts[currentFormat]);
	}
	
	
	/*
	 * Issues a notification to inform the user that server has sent a message.
	 */
	private static void generateNotification(Context context, String message) {
		Log.e(TAG, "MESSAGE = " + message);
		int icon = R.drawable.ic_launcher;
		long when = System.currentTimeMillis();
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(icon, message, when);

		String title = context.getString(R.string.app_name);

		Intent notificationIntent = new Intent(context, MainActivity.class);
		// set intent so it does not start a new activity
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent intent = PendingIntent.getActivity(context, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(context, title, message, intent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		// Play default notification sound
		// notification.defaults |= Notification.DEFAULT_SOUND;

		// Vibrate if vibrate is enabled
		// notification.defaults |= Notification.DEFAULT_VIBRATE;
		notificationManager.notify(0, notification);

	}
	
}
